package org.al.poc.generator;

import java.net.Socket;
import java.util.Date;

import org.al.poc.persistence.beans.Connection;
import org.al.poc.persistence.beans.Order;
import org.al.poc.persistence.beans.OrderTypeEnum;
import org.al.poc.sockets.SocketManager;

public class TestClient {
	
	
	protected Socket socket;

	
	public TestClient (Socket s) {
		this.socket = s;
	}

	public void start() throws Exception{
		

		for (int i = 0 ; i < 10 ; ++i) {
			
			socket = new Socket("127.0.0.1", 9292);
			SocketManager manager = new SocketManager(socket);
			
			Connection conn = new Connection(i, new Date(), null);
			manager.writeObject(conn);
			Object object = manager.readObject();
			if (! socket.isClosed()) socket.close();
			socket = null;
			System.out.println("connection received ? " + (object instanceof Connection));
			
			if (object instanceof Connection) {
				
				conn = (Connection) object;
				
//				System.out.println(i + " : sessionID = " + conn.getSessionId());
				
				socket = new Socket("127.0.0.1", 9292);
				manager = new SocketManager(socket);
				
				Order order = new Order(i, "APPLE", 100, 22.13, conn.getSessionId(), OrderTypeEnum.BUY);
				manager.writeObject(order);
				
				object = manager.readObject();
//				if (object instanceof Order) {
//					System.out.println(i + " order ID = " + ((Order) object).getOrderId());
//				}
				
				if (! socket.isClosed()) socket.close();
			}
			
		}
	}


	
	
	
	public static void main(String[] args) throws Exception {

//		if (args.length != 3) {
//			System.out.println("Usage: java Client serverAddress serverPort");
//			System.exit(0);
//		}
//
//		int port = Integer.parseInt(args[1]);
//
//		Socket socket = new Socket(args[0], port);
//		Socket socket = new Socket("127.0.0.1", 9090);

		new TestClient(null).start();
	}
}
